package com.qikecn.update;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

/**
 * 更新管理
 *
 * @author wangst
 * @version 2014年4月26日 上午10:49:04
 */
class UpdateManage {
    private static UpdateManage mInstance;
    private Dialog mDialogProgress;
    private ProgressBar mProgressBar;// 下载进度条
    private int mNewVersionCode;// 服务器最新版本号
    private String mSavePath;// 保存路径
    private String mDownlaodUrl;// 更新文件下载地址
    private String mUpdateMsg;// 更新提示语
    private boolean mForceUp = false;// 是否强制升级
    private Activity mActivity;
    private Handler mHandler = null;
    private final int SUCCESS = 100;
    private final int LOADING = 101;
    private final int FAILURE = 102;
    private long mTotal = 0L;// 下载文件总大小
    private long mCurrent = 0L;// 当前已下载大小
    //private HttpHandler<File> mHttpHandler;
    //private boolean mIsShowMsg = false;

    private HttpURLConnection httpUrl = null;
    private static boolean isDownloadRun = true;

    private static ExecutorService service = Executors.newSingleThreadExecutor();
    private static Future mFuture = null;

    private UpdateManage() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                // TODO Auto-generated method stub
                switch (msg.what) {
                    case SUCCESS:// 下载成功，安装
                        try {
                            //下载到私有目录无法安装的问题
                            if (mSavePath.toLowerCase().startsWith("/data/")){
                                File file = new File(mSavePath);
                                if (file.exists()){
                                    System.out.println("chmod dir and apk");
                                    String[] command = {"chmod", "777", file.getParentFile().getAbsolutePath()};
                                    ProcessBuilder builder = new ProcessBuilder(command);
                                    builder.start();

                                    String[] commandApk = {"chmod", "777", mSavePath};
                                    ProcessBuilder builderApk = new ProcessBuilder(commandApk);
                                    builderApk.start();
                                }
                            }

                            PackageUtils.installNormal(mActivity, mSavePath);
                            mDialogProgress.dismiss();
                            if (mForceUp) {
                                //System.exit(0);
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        break;
                    case LOADING:// 下载中 ，显示进度
                        //System.out.println("mTotal:"+mTotal+" mCurrent="+mCurrent);
                        if (mTotal > 0 && mCurrent > 0) {
                            int progress = (int) (((double) mCurrent)
                                    / ((double) mTotal) * 100);
                            mProgressBar.setProgress(progress);
                        }
                        break;
                    case FAILURE:// 下载失败，提示
                        if (msg.obj != null) {
                            Toast.makeText(mActivity, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        }
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 获取实例
     * @return
     */
    public static UpdateManage getInstance() {
        if (mInstance == null) {
            mInstance = new UpdateManage();
        }
        return mInstance;
    }

    public void checkUpdate(Activity activity, int newVersionCode,
                            String updateMsg, final String downloadUrl, final String savePath,
                            final int forceUpVersionCode, final long total) {
        mActivity = activity;
        mNewVersionCode = newVersionCode;
        mUpdateMsg = updateMsg;
        mDownlaodUrl = downloadUrl;
        mSavePath = savePath;
        mTotal = total;
        //mIsShowMsg = isShowMsg;
        if (mNewVersionCode > 0) {// 获取服务器版本号合法
            // 获取本地应用版本号
            int versionCode = PackageUtils.getAppVersionCode(activity);
            if (versionCode > 0) {// 本地版本号合法
                if (mNewVersionCode > versionCode) {// 发现新版本
                    if (forceUpVersionCode>=versionCode){
                        mForceUp = true;
                    }else {
                        mForceUp = false;
                    }
                    showUpdateMsg();
                    
                    /*if(isShowMsg){
                    	Toast.makeText(activity, "发现新版本", Toast.LENGTH_SHORT).show();
                    }*/
                    if(UpdateHttpUtil.mCallback != null){
                		UpdateHttpUtil.mCallback.onSuccess("发现新版本", true);
                	}
                }else {
	                /*if(isShowMsg){
	                	Toast.makeText(activity, "已是最新版本", Toast.LENGTH_SHORT).show();
	                }*/
	                if(UpdateHttpUtil.mCallback != null){
                		UpdateHttpUtil.mCallback.onSuccess("已是最新版本", false);
                	}
                }
            }
        }
    }

    /**
     * 显示升级提示
     */
    private void showUpdateMsg() {
        AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(mActivity, android.R.style.Theme_Dialog));
        alert.setTitle("发现新版本");
        alert.setMessage(mUpdateMsg);
        alert.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                showUpdateProgress();
                download();
            }
        });
        alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                if (mForceUp) {
                    //System.exit(0);
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        });
        alert.setCancelable(false);
        alert.show();
    }

    /**
     * 显示下载进度
     */
    private void showUpdateProgress() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(new ContextThemeWrapper(mActivity, android.R.style.Theme_Dialog));
        dialog.setTitle("更新进度");
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        //mProgressBar = (ProgressBar) inflater.inflate(R.layout.update_progressbar, null);

        mProgressBar = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal);
        mProgressBar.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        mProgressBar.setMax(100);
        mProgressBar.setProgress(0);

        dialog.setView(mProgressBar);
        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
                //mHttpHandler.cancel(true);
                isDownloadRun = false;
                if (mForceUp) {
                    //System.exit(0);
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            }
        });
        dialog.setCancelable(false);
        mDialogProgress = dialog.create();
        mDialogProgress.show();
    }

    /**
     * 下载
     */
    private void download() {
        /*HttpUtils httpUtils = new HttpUtils();
        mHttpHandler = httpUtils.download(mDownlaodUrl, mSavePath,
                new RequestCallBack<File>() {
                    @Override
                    public void onStart() {
                        // TODO Auto-generated method stub
                        super.onStart();
                        mTotal = 0L;
                        mCurrent = 0L;
                        makeDirs(mSavePath);
                    }

                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        // TODO Auto-generated method stub
                        super.onLoading(total, current, isUploading);
                        mTotal = total;
                        mCurrent = current;
                        Message message = mHandler.obtainMessage(LOADING);
                        message.sendToTarget();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {
                        // TODO Auto-generated method stub
                        Message message = mHandler.obtainMessage(SUCCESS);
                        message.sendToTarget();
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        // TODO Auto-generated method stub
                        Message message = mHandler.obtainMessage(FAILURE, msg);
                        message.sendToTarget();
                    }
                });*/

        mCurrent = 0;
        isDownloadRun = true;

        mFuture = service.submit(new Runnable() {
            @Override
            public void run() {
                saveToFile(mDownlaodUrl, mSavePath);
            }
        });

    }

    /**
     * 将HTTP资源另存为文件
     *
     * @param destUrl String
     * @param fileName String
     * @throws Exception
     */
    public void saveToFile(String destUrl, String fileName) {

        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        URL url = null;
        byte[] buf = new byte[8096];
        int size = 0;

        try{
            //建立链接
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            //连接指定的资源
            httpUrl.connect();
            //获取网络输入流
            bis = new BufferedInputStream(httpUrl.getInputStream());
            //建立文件
            File file = new File(fileName);
            if (file.exists()){

                if (file.length() == mTotal){//文件已经下载，直接安装
                    Message message = mHandler.obtainMessage(SUCCESS);
                    message.sendToTarget();
                    return;
                }

                file.delete();
            }
            if(!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();

            fos = new FileOutputStream(fileName);
            //fos = mActivity.openFileOutput(fileName, Activity.MODE_WORLD_READABLE);

            System.out.println("正在获取链接[" + destUrl + "]的内容...\n将其保存为文件[" + fileName + "]");
            //保存文件
            while (isDownloadRun && (size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
                mCurrent += size;
                Message message = mHandler.obtainMessage(LOADING);
                message.sendToTarget();
            }
            if (isDownloadRun){
                Message message = mHandler.obtainMessage(SUCCESS);
                message.sendToTarget();
            }
        }catch (Exception e){
            e.printStackTrace();
            Message message = mHandler.obtainMessage(FAILURE, e.getClass().getSimpleName());
            message.sendToTarget();
        }finally {
            try{
                if (fos != null)
                    fos.close();
                if (bis != null)
                    bis.close();
                if (httpUrl != null)
                    httpUrl.disconnect();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}